package logic

import (
	"context"
	"fmt"
	"mall/models/cache"
	"mall/models/mysql"

	"mall/mallrpc/internal/svc"
	"mall/mallrpc/mallrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type CartAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCartAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CartAddLogic {
	return &CartAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CartAddLogic) CartAdd(in *mallrpc.CartAddRequest) (*mallrpc.CartAddResponse, error) {
	// todo: add your logic here and delete this line

	var product mysql.Product
	err := mysql.DB.Debug().Where("id=?", in.ProductId).First(&product).Error
	if err != nil {
		return nil, fmt.Errorf("商品不存在")
	}
	if in.Quantity > product.Stock {
		return nil, fmt.Errorf("库存不足")
	}
	productMap := map[string]interface{}{
		"ProductId": in.ProductId,
		"quantity":  in.Quantity,
	}

	err = cache.CartAdd(in.UserId, in.ProductId, productMap)
	if err != nil {
		return nil, err
	}
	return &mallrpc.CartAddResponse{
		Success: false,
		Message: "购物车添加成功",
	}, nil
}
